package cn.edu.gznu.wecampus.core.weixin.service;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.annotation.JsonProperty;

import cn.edu.gznu.wecampus.core.weixin.entity.WeixinExpiresEntity;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Service
@DependsOn("accessTokenService")
@Slf4j
public class TicketService {
	
	@Autowired
	private WeixinService<TicketEntity> weixinService;
	
	@Autowired
	private AccessTokenService accessTokenService;
	
	@Getter
	@Setter
	public static class TicketEntity extends WeixinExpiresEntity {
		@JsonProperty("ticket")
		private String ticket;
	}

	@Getter
	@Setter
	private TicketEntity entity;
	
	@PostConstruct
	public void postContruct() {
		this.generate();
	}
	
	public void generate() {
		this.entity = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("access_token", accessTokenService.getEntity().getAccessToken());
		String url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?";
		TicketEntity ticket = weixinService.getForObject(url, TicketEntity.class, params);
		this.entity = ticket;
		log.info("ticket: " + this.entity.getTicket());
	}
	
	@Scheduled(cron = "0 0/10 * * * ? ")
	public void schedule() {
		if(this.entity == null || this.entity.isExpire()) {
			this.generate();
		}
	}
}
